import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:sonora/bloc/mine/sj_mine_bloc.dart';
import 'package:sonora/bloc/mine/sj_mine_event.dart';
import 'package:sonora/bloc/mine/sj_mine_state.dart';
import 'package:sonora/config/sj_app_initial.dart';
import 'package:sonora/models/sj_works_model.dart';
import 'package:sonora/shared/lib/constants/sj_colors.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/views/appbar/sj_appbar.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';

@RoutePage()
class SjMinePage extends StatefulWidget {
  const SjMinePage({super.key});
  @override
  State<SjMinePage> createState() => _SjMinePageState();
}

class _SjMinePageState extends State<SjMinePage> {
  late final SjMineBloc mineBloc = getit<SjMineBloc>();

  _SjMinePageState();

  @override
  void initState() {
    super.initState();
    mineBloc
      ..add(const SjMineEvent.loadedUserInfo())
      ..add(const SjMineEvent.loadWorksList());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true, // 使内容延伸到导航
        appBar: SjAppbar(
          backgroundColor: Colors.transparent, // 设置导航栏背景为透明
          elevation: 0, // 去除导航栏阴影
          actions: [
            IconButton(
              icon: Image.asset('assets/images/nav_setting.png'), // 右侧按钮
              onPressed: () {
                context.router.push(const SjSettingRoute());
              },
            ),
          ],
        ),
        body: BlocProvider<SjMineBloc>.value(
          value: mineBloc,
          child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/profile_bg_me.png'),
                  fit: BoxFit.cover,
                ),
              ),
              child: SafeArea(
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Column(children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            BlocBuilder<SjMineBloc, SjMineState>(
                                builder: (bContext, state) {
                              return Container(
                                width: 56, // Diameter (2 * radius) = 2 * 15
                                height: 56, // Diameter (2 * radius) = 2 * 15
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  image: DecorationImage(
                                    image: NetworkImage(state
                                            .userInfoData?.avatarUrl ??
                                        ''), // Replace with your avatar image URL
                                    fit: BoxFit.cover,
                                  ),
                                  border: Border.all(
                                    color: Colors.black, // Border color
                                    width: 2, // Border width
                                  ),
                                  boxShadow: const [
                                    BoxShadow(
                                      color: SjColors
                                          .themeColor, // Shadow color and opacity
                                      offset:
                                          Offset(1, 1), // Shadow offset (x, y)
                                    ),
                                  ],
                                ),
                              );
                            }),
                            const SizedBox(
                              width: 12,
                            ),
                            BlocBuilder<SjMineBloc, SjMineState>(
                                builder: (bContext, state) {
                              return Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(state.userInfoData?.nickname ?? '',
                                      style: SjTextStyle.customFontBlack20),
                                  Container(
                                    padding: const EdgeInsets.fromLTRB(8, 5, 8, 2),
                                    decoration: const BoxDecoration(
                                      color: SjColors.themeAColor,
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(10.0)),
                                    ),
                                    child: InkWell(
                                        onTap: () {
                                          ClipboardData data = ClipboardData(
                                              text:
                                                  state.userInfoData?.userId ??
                                                      '');
                                          Clipboard.setData(data);
                                          EasyLoading.showSuccess(
                                              'Copy Successfully');
                                        },
                                        child: Row(children: [
                                          Text(
                                            'ID : ${state.userInfoData?.userId ?? ''}',
                                            style:
                                                SjTextStyle.customFontTheme12,
                                          ),
                                          const SizedBox(
                                            width: 4,
                                          ),
                                          Padding(
                                            padding: EdgeInsets.only(bottom: 4),
                                            child: Image.asset(
                                                'assets/images/copy_icon.png'),
                                          ),
                                        ])),
                                  )
                                ],
                              );
                            })
                          ],
                        ),
                        InkWell(
                          child: Container(
                            padding: const EdgeInsets.fromLTRB(17, 8, 17, 4),
                            decoration: const BoxDecoration(
                                color: SjColors.blackColor,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(18))),
                            child: const Text(
                              'Edit',
                              style: SjTextStyle.customFontTheme16,
                            ),
                          ),
                          onTap: () {
                            context.router.push(const SjEditRoute()).then((value) {
                              mineBloc.add(const SjMineEvent.loadedUserInfo());
                            });
                            ;
                          },
                        )
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        InkWell(
                          child:
                              Image.asset('assets/images/follow_list_icon.png'),
                          onTap: () {
                            context.router.push(const SjFollowListRoute());
                          },
                        ),
                        InkWell(
                          child:
                              Image.asset('assets/images/block_list_icon.png'),
                          onTap: () {
                            context.router.push(const SjBlockListRoute());
                          },
                        ),
                        InkWell(
                          child: Image.asset('assets/images/about_icon.png'),
                          onTap: () {
                            context.router.push(const SjAboutRoute());
                          },
                        )
                      ],
                    ),
                    const SizedBox(
                      height: 8,
                    ),
                    InkWell(
                      onTap: () {
                        context.router
                            .push(SjCoinShopRoute())
                            .then((value) {
                          mineBloc.add(const SjMineEvent.loadedUserInfo());
                        });
                      },
                      child: Stack(children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset('assets/images/coins_icon.png')
                          ],
                        ),
                        Positioned(
                          right: 0,
                          top: 30,
                          width: 200,
                          child: Column(children: [
                            const Text(
                              'My Cions',
                              style: SjTextStyle.customFontBlack14,
                            ),
                            BlocBuilder<SjMineBloc, SjMineState>(
                                builder: (bContext, state) {
                              return Text(
                                '${state.userInfoData?.availableCoins ?? 0}',
                                style: SjTextStyle.customFontBlack32,
                              );
                            })
                          ]),
                        )
                      ]),
                    ),
                    Expanded(
                      child: BlocBuilder<SjMineBloc, SjMineState>(builder: (context, state) {
                        if (state.worksList == null || state.worksList!.isEmpty) {
                          return  Image.asset('assets/images/empty_icon.png');
                        } else {
                          return MasonryGridView.count(
                            padding: const EdgeInsets.symmetric(vertical: 20),
                          crossAxisCount: 2,
                          // 设置列数
                          mainAxisSpacing: 8,
                          crossAxisSpacing: 8,
                          itemCount: state.worksList?.length ?? 0,
                          itemBuilder: (context, index) {
                            SjWorksModel? data = state.worksList?.elementAt(index);
                            return GestureDetector(
                              onTap: (){
                                context.router.push(SjArticleDetailRoute(data: data!));
                              },
                              child: index == 1
                                  ? _buildContentCard(data, index)
                                  : _buildContentCard1(data, index)
                            );
                          },
                        );
                        }
                      })
                    )
                  ]),
                ),
              )),
        ));
  }


  Widget _buildContentCard(SjWorksModel? data, int index) {
    return Column(
      children: [
        Image.asset('assets/images/my_article_icon.png'),
        (data?.isPlaceholder != null && data?.isPlaceholder == true) ? const SizedBox() : Padding(
            padding: const EdgeInsets.all(2),
            child: Stack(
              children: [
                Container(
                  padding: const EdgeInsets.all(3),
                  decoration: const BoxDecoration(
                      color: SjColors.blackColor, boxShadow: [BoxShadow(color: SjColors.iconWhiteColor, offset: Offset(2, 2))]),
                  child: Container(
                    width: double.infinity,
                    height: 215,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: FileImage(File(data?.cover ?? '')),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(14.0),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [],
                      ),
                    ),
                  ),
                ),
                Positioned(
                  top: 8,
                  right: 8,
                  width: 28,
                  height: 28,
                  child: InkWell(
                    child: 
                        Image.asset('assets/images/post_delete.png'),
                    onTap: () {
                      mineBloc.add(SjMineEvent.deleteWorks(worksId: data?.worksId ?? ''));
                    },
                  ),
                ),
                Positioned(
                  left: 0,
                  bottom: 0,
                  child: Stack(
                    children: [
                      Positioned.fill(
                        left: 0,
                        bottom: 0,
                        child: Container(
                          height: 17,
                          decoration: const BoxDecoration(
                              image: DecorationImage(
                                  // alignment: Alignment.bottomLeft,
                                  image: AssetImage('assets/images/home_name_bg.png'),
                                  fit: BoxFit.fitWidth)),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 5),
                        child: Container(
                          width: 30, // Diameter (2 * radius) = 2 * 15
                          height: 30, // Diameter (2 * radius) = 2 * 15
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            image: DecorationImage(
                              image: NetworkImage(data?.avatar ?? ''), // Replace with your avatar image URL
                              fit: BoxFit.cover,
                            ),
                            border: Border.all(
                              color: Colors.black, // Border color
                              width: 1, // Border width
                            ),
                            boxShadow: const [
                              BoxShadow(
                                color: Colors.white, // Shadow color and opacity
                                offset: Offset(1, 1), // Shadow offset (x, y)
                              ),
                            ],
                          ),
                        ),
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const SizedBox(
                            width: 35,
                          ),
                          Text(
                            data?.nickname ?? '',
                            style: SjTextStyle.customFontBlack24,
                          )
                        ],
                      )
                    ],
                  ),
                )
              ],
            ))
      ],
    );
  }

  Widget _buildContentCard1(SjWorksModel? data, index) {
    return Padding(
        padding: const EdgeInsets.all(2),
        child: Stack(
          children: [
            Container(
              padding: const EdgeInsets.all(3),
              decoration:
                  const BoxDecoration(color: SjColors.blackColor, boxShadow: [BoxShadow(color: SjColors.iconWhiteColor, offset: Offset(2, 2))]),
              child: Container(
                width: double.infinity,
                height: 215,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(data?.cover ?? ''),
                    fit: BoxFit.cover,
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(14.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [],
                  ),
                ),
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              width: 28,
              height: 28,
              child: InkWell(
                child: Image.asset('assets/images/post_delete.png'),
                onTap: () {
                  mineBloc.add(SjMineEvent.deleteWorks(worksId: data?.worksId ?? ''));
                },
              ),
            ),
            Positioned(
              left: 0,
              bottom: 0,
              child: Stack(
                children: [
                  Positioned.fill(
                    left: 0,
                    bottom: 0,
                    child: Container(
                      height: 17,
                      decoration: const BoxDecoration(
                          image: DecorationImage(
                              // alignment: Alignment.bottomLeft,
                              image: AssetImage('assets/images/home_name_bg.png'),
                              fit: BoxFit.fitWidth)),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 5),
                    child: Container(
                      width: 30, // Diameter (2 * radius) = 2 * 15
                      height: 30, // Diameter (2 * radius) = 2 * 15
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        image: DecorationImage(
                          image: NetworkImage(data?.avatar ?? ''), // Replace with your avatar image URL
                          fit: BoxFit.cover,
                        ),
                        border: Border.all(
                          color: Colors.black, // Border color
                          width: 1, // Border width
                        ),
                        boxShadow: const [
                          BoxShadow(
                            color: Colors.white, // Shadow color and opacity
                            offset: Offset(1, 1), // Shadow offset (x, y)
                          ),
                        ],
                      ),
                    ),
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      const SizedBox(
                        width: 35,
                      ),
                      Text(
                        data?.nickname ?? '',
                        style: SjTextStyle.customFontBlack24,
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ));
  }

}
